package registry

import (
	"errors"
	"fmt"
	"gamesdk/common/log"
	"gamesdk/common/registry"
	"strings"
)

const (
	_PREFIX_             = "qydc-"
	_REGISTRY_MANAGER    = _PREFIX_ + "game-manager"
	_REGISTRY_GATEWAY    = _PREFIX_ + "game-gateway"
	_REGISTRY_REDIS      = _PREFIX_ + "game-redis"
	_REGISTRY_MYSQL      = _PREFIX_ + "game-mysql"
	_REGISTRY_KAFKA      = _PREFIX_ + "game-kafka"
	_REGISTRY_ELK        = _PREFIX_ + "game-elk"
	_REGISTRY_SHPLATFORM = _PREFIX_ + "game-shplatorm"
	_REGISTRY_NATS       = _PREFIX_ + "game-nats"
	_REDIS_META_PASS     = "pass"
	_MYSQL_META_USER     = "user"
	_MYSQL_META_PASS     = "pass"
	_MYSQL_META_DB       = "db"
)

//获取网关ID
func _gatewayRegistryID(gameid int64) string { return fmt.Sprintf("%s-%d", _REGISTRY_GATEWAY, gameid) }

var cli *registry.Client

func Init(addr string) error {
	var err error
	cli, err = registry.NewClient(addr)
	if err != nil {
		log.Warn("registry client error : %s", err)
		return err
	}
	return nil
}

func RegisterManager(ip string, port int) error {
	return cli.Agent().ServiceRegister(&registry.ServiceRegistration{
		ID:      fmt.Sprintf("%s-%s", _REGISTRY_MANAGER, ip),
		Name:    _REGISTRY_MANAGER,
		Address: ip,
		Port:    port,
	})
}

func ServiceManager() (ip string, port int, err error) {
	sr, e := cli.Agent().Services(_REGISTRY_MANAGER)
	if e != nil {
		return "", 0, e
	}
	if len(*sr) != 1 {
		return "", 0, errors.New("没找到Manager")
	}
	return (*sr)[0].Address, (*sr)[0].Port, nil
}
func DeregisterManager(ip string) error {
	return cli.Agent().ServiceDeregister(fmt.Sprintf("%s-%s", _REGISTRY_MANAGER, ip))
}

func RegisterSHPlatform(ip string) error {
	return cli.Agent().ServiceRegister(&registry.ServiceRegistration{
		ID:      _REGISTRY_SHPLATFORM,
		Name:    _REGISTRY_SHPLATFORM,
		Address: ip,
	})
}

func ServiceSHPlatform() (ip string, err error) {
	sr, e := cli.Agent().Service(_REGISTRY_SHPLATFORM)
	if e != nil {
		return "", e
	}
	return sr.Address, nil
}
func DeregisterSHPlatform() error {
	return cli.Agent().ServiceDeregister(_REGISTRY_SHPLATFORM)
}

func RegisterNats(addr string) error {
	port := 0
	ip := ""
	arr := strings.Split(addr, ":")
	if len(arr) != 2 {
		log.Warn("地址解析错误 :%s", addr)
		return errors.New("地址解析错误")
	}
	ip = arr[0]
	fmt.Sscanf(arr[1], "%d", &port)
	return cli.Agent().ServiceRegister(&registry.ServiceRegistration{
		ID:      _REGISTRY_NATS,
		Name:    _REGISTRY_NATS,
		Address: ip,
		Port:    port,
	})
}

func ServiceNats() (ip string, port int, err error) {
	sr, e := cli.Agent().Service(_REGISTRY_NATS)
	if e != nil {
		return "", 0, e
	}
	return sr.Address, sr.Port, nil
}
func DeregisterNats() error {
	return cli.Agent().ServiceDeregister(_REGISTRY_NATS)
}

func RegisterGateway(ip string, port int, gameid int64, name string) error {
	return cli.Agent().ServiceRegister(&registry.ServiceRegistration{
		ID:      _gatewayRegistryID(gameid),
		Name:    _gatewayRegistryID(gameid),
		Address: ip,
		Port:    port,
		Tags:    []string{name},
	})
}
func RegisterGateways(ip string, port int, gameid int64, name string) error {
	return cli.Agent().ServiceRegister(&registry.ServiceRegistration{
		ID:      _gatewayRegistryID(gameid) + fmt.Sprintf("_%s_%d", ip, port),
		Name:    _gatewayRegistryID(gameid),
		Address: ip,
		Port:    port,
		Tags:    []string{name},
	})
	//return cli.Agent().PassTTL(_gatewayRegistryID(gameid) + fmt.Sprintf("_%s_%d", ip, port))
}
func ServiceGateway(gameid int64) (ip string, port int, err error) {
	sr, e := cli.Agent().Service(_gatewayRegistryID(gameid))
	if e != nil {
		return "", 0, e
	}
	return sr.Address, sr.Port, nil
}

func ServiceGateways(gameid int64) (*[]registry.ServiceRegistration, error) {
	return cli.Agent().Services(_gatewayRegistryID(gameid))
}

func DeregisterGateway(gameid int64) error {
	return cli.Agent().ServiceDeregister(_gatewayRegistryID(gameid))
}

func DeregisterGateways(gameid int64, ip string, port int) error {
	return cli.Agent().ServiceDeregister(_gatewayRegistryID(gameid) + fmt.Sprintf("_%s_%d", ip, port))
}

func RegisterKafka(addr string) error {
	port := 0
	ip := ""
	arr := strings.Split(addr, ":")
	if len(arr) != 2 {
		log.Warn("地址解析错误")
		return errors.New("地址解析错误")
	}
	ip = arr[0]
	fmt.Sscanf(arr[1], "%d", &port)
	return cli.Agent().ServiceRegister(&registry.ServiceRegistration{
		ID:      _REGISTRY_KAFKA,
		Name:    _REGISTRY_KAFKA,
		Address: ip,
		Port:    port,
	})
}

func ServiceKafka() (ip string, port int, err error) {
	sr, e := cli.Agent().Service(_REGISTRY_KAFKA)
	if e != nil {
		return "", 0, e
	}
	return sr.Address, sr.Port, nil
}

func DeregisterKafka() error {
	return cli.Agent().ServiceDeregister(_REGISTRY_KAFKA)
}

func RegisterRedis(addr, pass string) error {
	port := 0
	ip := ""
	arr := strings.Split(addr, ":")
	if len(arr) != 2 {
		log.Warn("地址解析错误")
		return errors.New("地址解析错误")
	}
	ip = arr[0]
	fmt.Sscanf(arr[1], "%d", &port)
	meta := make(map[string]string, 0)
	meta[_REDIS_META_PASS] = pass
	return cli.Agent().ServiceRegister(&registry.ServiceRegistration{
		ID:      _REGISTRY_REDIS,
		Name:    _REGISTRY_REDIS,
		Address: ip,
		Port:    port,
		Meta:    meta,
	})
}

func ServiceRedis() (ip, pass string, port int, err error) {
	sr, e := cli.Agent().Service(_REGISTRY_REDIS)
	if e != nil {
		return "", "", 0, e
	}
	return sr.Address, sr.Meta[_REDIS_META_PASS], sr.Port, nil
}
func DeregisterRedis() error {
	return cli.Agent().ServiceDeregister(_REGISTRY_REDIS)
}

type MysqlInfo struct {
	Addr string
	Pass string
	User string
	Db   string
}

func RegisterMysql(info MysqlInfo) error {
	var port int
	var ip string
	arr := strings.Split(info.Addr, ":")
	if len(arr) != 2 {
		log.Warn("地址解析错误")
		return errors.New("地址解析错误")
	}
	ip = arr[0]
	fmt.Sscanf(arr[1], "%d", &port)
	meta := make(map[string]string, 0)
	meta[_MYSQL_META_PASS] = info.Pass
	meta[_MYSQL_META_USER] = info.User
	meta[_MYSQL_META_DB] = info.Db
	return cli.Agent().ServiceRegister(&registry.ServiceRegistration{
		ID:      _REGISTRY_MYSQL,
		Name:    _REGISTRY_MYSQL,
		Address: ip,
		Port:    port,
		Meta:    meta,
	})
}

func ServiceMysql() (*MysqlInfo, error) {
	info := new(MysqlInfo)
	sr, e := cli.Agent().Service(_REGISTRY_MYSQL)
	if e != nil {
		return nil, e
	}
	info.User = sr.Meta[_MYSQL_META_USER]
	info.Pass = sr.Meta[_MYSQL_META_PASS]
	info.Db = sr.Meta[_MYSQL_META_DB]
	info.Addr = fmt.Sprintf("%s:%d", sr.Address, sr.Port)
	return info, nil
}

func DeregisterMysql() error {
	return cli.Agent().ServiceDeregister(_REGISTRY_MYSQL)
}

func RegisterElk(addr string) error {
	port := 0
	ip := ""
	arr := strings.Split(addr, ":")
	if len(arr) != 2 {
		log.Warn("地址解析错误")
		return errors.New("地址解析错误")
	}
	ip = arr[0]
	fmt.Sscanf(arr[1], "%d", &port)
	return cli.Agent().ServiceRegister(&registry.ServiceRegistration{
		ID:      _REGISTRY_ELK,
		Name:    _REGISTRY_ELK,
		Address: ip,
		Port:    port,
	})
}

func ServiceElk() (ip string, port int, err error) {
	sr, e := cli.Agent().Service(_REGISTRY_ELK)
	if e != nil || sr.Port == 0 {
		return "", 0, errors.New("没有相关信息")
	}
	return sr.Address, sr.Port, nil
}

func DeregisterElk() error {
	return cli.Agent().ServiceDeregister(_REGISTRY_ELK)
}
